package com.zjj.disk.utils;

import com.sun.mail.util.MailSSLSocketFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

/**
 * @author zjj
 * @create 2023-03-25 22:15
 */
@Component
public class MailUtil {
    @Value("${spring.mail.username}")
    private String mailUsername;
    @Value("${spring.mail.host}")
    private String host;
    @Value("${spring.mail.protocol}")
    private String protocol;
    @Value("${spring.mail.port}")
    private String port;
    @Value("${spring.mail.password}")
    private String password;
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private TemplateEngine templateEngine;


    @Async
    public void sendMail(String activationUrl, String email) {
        try {
            Properties properties = new Properties();
            properties.setProperty("mail.host", host); // 邮件服务器地址
            properties.setProperty("mail.transport.protocol", protocol); // 设置邮件发送协议
            properties.setProperty("mail.smtp.port", port); // 端口
            properties.setProperty("mail.smtp.auth", "false"); // 邮件服务身份验证
            properties.setProperty("mail.smtp.ssl.enable", "true"); // 邮件ssl验证

            //创建一个session对象
            Session session = Session.getDefaultInstance(properties);
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            properties.put("mail.smtp.ssl.socketFactory", sf);
            //开启debug模式
            session.setDebug(true);
            //获取连接对象
            Transport transport = session.getTransport();
            //连接服务器
            transport.connect(host, mailUsername, password);
            //创建邮件对象
            MimeMessage mimeMessage = new MimeMessage(session);
            //邮件发送人
            mimeMessage.setFrom(new InternetAddress(mailUsername));
            //邮件接收人
            mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(email));
            //邮件标题
            mimeMessage.setSubject("disk账户激活注册");
            //邮件内容
            mimeMessage.setContent("您的激活链接是：<b><a href='" + activationUrl + "'>" + activationUrl + "</a></b> 点击进行激活<br>（有效期为5分钟）", "text/html;charset=UTF-8");
            //发送邮件
            transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
            //关闭连接
            transport.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    //  @Async
    /*public void sendMail(String activationUrl, String email){
        //创建邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            // 设置邮件主题
            helper.setSubject("disk账户激活注册");
            // 设置邮件发送者
            helper.setFrom(mailUsername);
            // 设置接收方
            helper.setTo(email);
            // 设置抄送人
            // helper.setCc();
            // 设置秘密抄送人
            // helper.setBcc();
            // 设置邮件发送日期
            helper.setSentDate(new Date());
            // 创建上下文环境
//            Context context = new Context();
//            context.setVariable("activationUrl", activationUrl);
//            String text = templateEngine.process("active-account.html", context);
            //设置邮件正文
            helper.setText("您的激活链接是：<b><a href='"+activationUrl+"'>"+activationUrl+"</a></b> 点击进行激活<br>（有效期为5分钟）",true);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
        //发送邮件
        javaMailSender.send(mimeMessage);
    }*/

    @Async
    public void sendValidationCode(String code, String email, Integer status) {
        //创建邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            // 设置邮件主题
            if (status == 1 || status == 2) {
                helper.setSubject("disk账户修改邮箱");
            } else if (status == 3) {
                helper.setSubject("disk注销账户");
            }
            // 设置邮件发送者
            helper.setFrom(mailUsername);
            // 设置接收方
            helper.setTo(email);
            // 设置抄送人
            // helper.setCc();
            // 设置秘密抄送人
            // helper.setBcc();
            // 设置邮件发送日期
            helper.setSentDate(new Date());
            // 创建上下文环境
//            Context context = new Context();
//            context.setVariable("activationUrl", activationUrl);
//            String text = templateEngine.process("active-account.html", context);
            //设置邮件正文
            helper.setText("您的验证码是：<b>" + code + "</b><br>（有效期为120秒）", true);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
        //发送邮件
        javaMailSender.send(mimeMessage);
    }
}
